//package com.example.pt.service;
//
//import com.example.pt.entity.Peer;
//import com.example.pt.entity.Torrent;
//import com.example.pt.entity.User;
//import com.example.pt.repository.PeerRepository;
//import com.example.pt.repository.TorrentRepository;
//import com.example.pt.repository.UserRepository;
//import jakarta.transaction.Transactional;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Service;
//import com.dampcake.bencode.Bencode;
//
//import java.io.IOException;
//import java.net.Inet4Address;
//import java.net.InetAddress;
//import java.net.UnknownHostException;
//import java.nio.ByteBuffer;
//import java.nio.charset.StandardCharsets;
//import java.time.Duration;
//import java.time.Instant;
//import java.util.*;
//import java.util.concurrent.ConcurrentHashMap;
//
//import static com.mysql.cj.conf.PropertyKey.logger;
//
//@Service
//public class TrackerService {
//
//    @Value("${tracker.announce-interval:1800}")
//    private int announceInterval;
//
//    @Value("${tracker.peer-cleanup-interval:300}")
//    private int peerCleanupInterval;
//
//    private final PeerRepository peerRepository;
//    private final TorrentRepository torrentRepository;
//
//    // 内存缓存提高性能
//    private final Map<String, List<Peer>> peersByTorrent = new ConcurrentHashMap<>();
//    private final Bencode bencode = new Bencode(StandardCharsets.UTF_8);
//
//    @Autowired
//    public TrackerService(PeerRepository peerRepository,
//                          TorrentRepository torrentRepository) {
//        this.peerRepository = peerRepository;
//        this.torrentRepository = torrentRepository;
//
//        loadPeersFromDatabase();
//    }
//
////    @Transactional
////    public void processAnnounce(String infoHash, String peerId, String ip, int port,
////                                long uploaded, long downloaded, long left, String event) {
////        // 处理"stopped"事件
////        if ("stopped".equals(event)) {
////            peerRepository.deleteByTorrentInfoHashAndPeerId(infoHash, peerId);
////            updateTorrentStats(infoHash);
////            return;
////        }
////        // 1. 查找或创建Torrent记录
////        Optional<Torrent> torrentOpt = torrentRepository.findById(infoHash);
////        Torrent torrent = torrentOpt.orElseGet(() -> {
////            Torrent newTorrent = new Torrent();
////            newTorrent.setInfoHash(infoHash);
////            newTorrent.setName("Unknown Torrent"); // 可以后续更新
////            return torrentRepository.save(newTorrent);
////        });
////
////        // 2. 处理Peer记录
////        Peer peer = peerRepository.findByTorrentInfoHashAndPeerId(infoHash, peerId)
////                .orElseGet(() -> {
////                    Peer newPeer = new Peer();
////                    newPeer.setTorrent(torrent);
////                    newPeer.setPeerId(peerId);
////                    newPeer.setIp(ip);
////                    newPeer.setPort(port);
////                    return newPeer;
////                });
////
////        // 更新Peer信息
////        peer.setUploaded(uploaded);
////        peer.setDownloaded(downloaded);
////        peer.setLeft(left);
////        peer.setSeeder(left == 0); // 如果left=0表示已完成下载(做种者)
////        peer.setLastUpdated(Instant.now());
////
////        peerRepository.save(peer);
////
////        // 3. 如果是"completed"事件，更新用户统计数据
////        if ("completed".equals(event)) {
////            // 这里可以添加用户统计更新逻辑
////        }
////
////        // 3. 更新Torrent的seeders/leechers统计
////        updateTorrentStats(infoHash);
////    }
//
//    private void updateTorrentStats(String infoHash) {
//        List<Peer> peers = getActivePeers(infoHash);
//        long seeders = peers.stream().filter(Peer::isSeeder).count();
//        long leechers = peers.size() - seeders;
//
//        torrentRepository.findById(infoHash).ifPresent(torrent -> {
//            torrent.setUploadCount((int) seeders);
//            torrent.setDownloadCount((int) leechers);
//            torrentRepository.save(torrent);
//        });
//    }
//
//    @Scheduled(fixedRate = 3600000) // 每小时清理一次过期peer
//    @Transactional
//    public void cleanupExpiredPeers() {
//        Instant cutoff = Instant.now().minusSeconds(2700); // 45分钟未更新的peer视为过期
//        peerRepository.deleteByLastUpdatedBefore(cutoff);
//    }
//
//
//    private void loadPeersFromDatabase() {
//        List<Peer> allPeers = peerRepository.findAll();
//        allPeers.forEach(peer -> {
//            String infoHash = peer.getTorrent().getInfoHash();
//            peersByTorrent.computeIfAbsent(infoHash, k -> new ArrayList<>()).add(peer);
//        });
//    }
//
//
//
//    public List<Peer> getActivePeers(String infoHash) {
//        // 定义peer活跃的阈值(30分钟内更新过的视为活跃)
//        Instant cutoff = Instant.now().minusSeconds(1800);
//        return peerRepository.findActivePeersByTorrent(infoHash, cutoff);
//    }
//}
